package pl.com.like.sequoia.dao.bio;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.Assert;

import pl.com.like.sequoia.dao.GenericDao;
import pl.com.like.sequoia.model.bio.BioObjectHandler;
import pl.com.like.sequoia.model.bio.enums.FileTypeEnum;

public class BioObjectHandlerDao extends GenericDao<BioObjectHandler, Long> implements IBioObjectHandlerDao {

	public BioObjectHandlerDao() {
		super(BioObjectHandler.class);
	}

	public void commit() {
		getSession().getTransaction().commit();
	}

	/** {@inheritDoc} */
	public Boolean exists(String objectId, FileTypeEnum type) {
		Boolean exists = Boolean.FALSE;
		BioObjectHandler object = get(objectId, type);
		if (null != object) {
			exists = Boolean.TRUE;
		}
		return exists;
	}

	/**
	 * {@inheritDoc}
	 */
	public BioObjectHandler get(String objectId, FileTypeEnum type) {
		BioObjectHandler object = (BioObjectHandler) getCriteria().add(Expression.eq("name", objectId)).add(
				Expression.eq("fileType", type)).uniqueResult();
		return object;
	}

	@SuppressWarnings("unchecked")
	public List<BioObjectHandler> searchObjects(String patternId, FileTypeEnum type, Boolean extended, Integer maxSize,
			Integer firstResult) {
		Assert.hasLength(patternId);
		Assert.notNull(type);
		Criteria crit = getCriteria().add(Expression.eq("fileType", type));
		if (Boolean.TRUE.equals(extended)) {
			crit.createAlias("bioParams", "param", Criteria.LEFT_JOIN);
			crit.add(Restrictions.or(Expression.like("name", patternId), Expression.like("param.value", patternId)));
		} else {
			crit.add(Expression.like("name", patternId));
		}
		if (firstResult != null && firstResult > 0) {
			crit.setFirstResult(firstResult);
		}
		if (maxSize != null && maxSize > 0) {
			crit.setMaxResults(maxSize);
		}
		crit.addOrder(Order.asc("name"));
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public List<BioObjectHandler> searchObjectsWithoutParams(Integer maxSize) {
		FileTypeEnum type = FileTypeEnum.PDB_ZIP;
		Criteria crit = getCriteria().add(Expression.eq("fileType", type));
		crit.add(Expression.eq("checked", Boolean.FALSE));
		if (maxSize != null && maxSize > 0) {
			crit.setMaxResults(maxSize);
		}
		crit.addOrder(Order.asc("name"));
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return crit.list();
	}

}
